// -----------------------------------------------------------------------------
// | © AlgoPoint                                                               |
// | Indicator: CUSUM Trend [AlgoPoint]                                        |
// | Developer: Harmony Algo & AlgoPoint Collaboration                         |
// -----------------------------------------------------------------------------

//@version=5
indicator("CUSUM Trend", shorttitle="CUSUM Trend", overlay=true, max_labels_count=500)

// ==========================================
// 1. USER INPUTS (LUXALGO STYLE UI)
// ==========================================
grp_main = "Main Settings"
string sensitivity = input.string("Balanced (Swing)", "Sensitivity", options=["Fast (Day Trade)", "Balanced (Swing)", "Slow (Trend)"], group=grp_main, tooltip="Day Trade produces more signals but has fakeout risks. Trend waits for massive moves.")
bool show_dash = input.bool(true, "Show Dashboard", group=grp_main)

// ==========================================
// 2. QUANT VARIABLES & CUSUM ENGINE
// ==========================================
var int base_len = 21
var float k_mult = 0.5
var float h_mult = 3.0

if sensitivity == "Fast (Day Trade)"
    base_len := 14
    k_mult := 0.4
    h_mult := 2.0
else if sensitivity == "Balanced (Swing)"
    base_len := 21
    k_mult := 0.5
    h_mult := 3.0
else if sensitivity == "Slow (Trend)"
    base_len := 50
    k_mult := 0.6
    h_mult := 4.0

float hma_base = ta.hma(close, base_len)
float residual = close - hma_base
float res_std = ta.stdev(residual, base_len)

// Prevent division by zero or NA
res_std := na(res_std) or res_std == 0 ? 0.001 : res_std

float k_drift = res_std * k_mult
float h_thresh = res_std * h_mult

var float bullPressure = 0.0 
var float bearPressure = 0.0 

bullPressure := math.max(0, nz(bullPressure[1]) + residual - k_drift)
bearPressure := math.max(0, nz(bearPressure[1]) - residual - k_drift)

// No-Repaint logic: Only confirm signals when the bar is closed
bool isConfirmed = barstate.isconfirmed
bool trig_bull = bullPressure > h_thresh and isConfirmed
bool trig_bear = bearPressure > h_thresh and isConfirmed

if trig_bull or trig_bear
    bullPressure := 0.0
    bearPressure := 0.0

// ==========================================
// 3. REGIME & TRAILING STOP LOGIC
// ==========================================
var int regime = 0 // 1: Bull, -1: Bear, 0: Ranging

float up_band = hma_base + h_thresh
float dn_band = hma_base - h_thresh

// Breakout validation with No-Repaint
if trig_bull
    regime := 1
else if trig_bear
    regime := -1
else if regime == 1 and close < dn_band and isConfirmed
    regime := 0
else if regime == -1 and close > up_band and isConfirmed
    regime := 0

// ==========================================
// 4. VISUALIZATION & ALGOPOINT PALETTE
// ==========================================
// AlgoPoint Color Palette
color col_bull = #2ee319
color col_bear = #f31623
color col_range = #7f49de

color cloud_col = regime == 1 ? color.new(col_bull, 85) : regime == -1 ? color.new(col_bear, 85) : color.new(col_range, 85)

p_up = plot(up_band, color=color.new(color.gray, 70), title="Upper Band")
p_dn = plot(dn_band, color=color.new(color.gray, 70), title="Lower Band")
fill(p_up, p_dn, color=cloud_col, title="CUSUM Cloud")

// Gradient Candle Coloring based on Pressure
float max_pressure = math.max(bullPressure, bearPressure)
float pressure_pct = math.min((max_pressure / h_thresh) * 100, 100)

color candle_bull = color.from_gradient(pressure_pct, 0, 100, color.new(col_bull, 60), col_bull)
color candle_bear = color.from_gradient(pressure_pct, 0, 100, color.new(col_bear, 60), col_bear)
color candle_range = color.new(col_range, 30)

color candle_col = regime == 1 ? candle_bull : regime == -1 ? candle_bear : candle_range
barcolor(candle_col, title="Trend Candles")

// Trailing Stop Line
float trail_stop = regime == 1 ? dn_band : regime == -1 ? up_band : na
plot(trail_stop, color=candle_col, style=plot.style_circles, linewidth=2, title="Trailing Stop")

// ATR Based Professional Signals
bool bull_start = regime == 1 and regime[1] != 1
bool bear_start = regime == -1 and regime[1] != -1

float y1 = low - (ta.atr(30) * 1.05)
float y2 = high + (ta.atr(30) * 1.05)

if bull_start
    label.new(bar_index, y1, "Buy", color=#018208, style=label.style_label_up, textcolor=color.white, size=size.normal)
if bear_start
    label.new(bar_index, y2, "Sell", color=#d12208, style=label.style_label_down, textcolor=color.white, size=size.normal)

// ==========================================
// 5. HIBRID DASHBOARD
// ==========================================
string status_txt = regime == 1 ? "Bullish" : regime == -1 ? "Bearish" : "Ranging"
color status_col = regime == 1 ? col_bull : regime == -1 ? col_bear : col_range

string press_txt = pressure_pct > 80 ? "HIGH (Warning)" : pressure_pct > 50 ? "Rising" : "Stable"
color press_col = pressure_pct > 80 ? color.orange : color.white

var table dash = table.new(position.top_right, 2, 4, bgcolor=color.new(color.black, 15), border_width=1, border_color=color.new(color.gray, 80))

if barstate.islast and show_dash
    table.cell(dash, 0, 0, "CUSUM Panel", text_color=color.gray, text_size=size.small)
    table.cell(dash, 1, 0, "", text_color=color.gray, text_size=size.small)

    table.cell(dash, 0, 1, "Market State", text_color=color.white, text_size=size.small)
    table.cell(dash, 1, 1, status_txt, text_color=status_col, text_size=size.small)

    table.cell(dash, 0, 2, "Breakout Pressure", text_color=color.white, text_size=size.small)
    table.cell(dash, 1, 2, press_txt, text_color=press_col, text_size=size.small)

    table.cell(dash, 0, 3, "Trailing Stop", text_color=color.white, text_size=size.small)
    table.cell(dash, 1, 3, regime == 0 ? "Waiting..." : str.tostring(trail_stop, "#.####"), text_color=status_col, text_size=size.small)

// ==========================================
// 6. ALERTS & WEBHOOK AUTOMATION
// ==========================================
// Standard UI Alerts
alertcondition(bull_start, title="🟢 BUY Signal", message="CUSUM trend broke upward. Bull trend starting!")
alertcondition(bear_start, title="🔴 SELL Signal", message="CUSUM trend broke downward. Bear trend starting!")

// Dynamic JSON Alerts for Bot Automation
if bull_start
    alert('{"action": "buy", "ticker": "' + syminfo.ticker + '", "price": ' + str.tostring(close) + ', "type": "bull_breakout"}', alert.freq_once_per_bar_close)
    
if bear_start
    alert('{"action": "sell", "ticker": "' + syminfo.ticker + '", "price": ' + str.tostring(close) + ', "type": "bear_breakout"}', alert.freq_once_per_bar_close)